package com.smartlight.godlight.widget;

import android.content.Context;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ListView;

// 自定义HorizontalListView类
public class HorizontalListView extends ListView {
    public HorizontalListView(Context context) {
        super(context);
        initView();
    }

    public HorizontalListView(Context context, AttributeSet attrs) {
        super(context, attrs);
        initView();
    }

    private void initView() {
        setHorizontalScrollBarEnabled(true);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        int totalLength = 0;
        int maxChildHeight = 0;
        int childState = 0;
        int count = getChildCount();
        for (int i = 0; i < count; i++) {
            View child = getChildAt(i);
            measureChild(child, widthMeasureSpec, heightMeasureSpec);
            totalLength += child.getMeasuredWidth();
            maxChildHeight = Math.max(maxChildHeight, child.getMeasuredHeight());
            childState = combineMeasuredStates(childState, child.getMeasuredState());
        }
        totalLength += getPaddingLeft() + getPaddingRight();
        maxChildHeight += getPaddingTop() + getPaddingBottom();
        setMeasuredDimension(resolveSizeAndState(totalLength, widthMeasureSpec, childState),
                resolveSizeAndState(maxChildHeight, heightMeasureSpec, childState << MEASURED_HEIGHT_STATE_SHIFT));
    }

    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        int childLeft = getPaddingLeft();
        final int verticalGravity = getVerticalFadingEdgeLength();
        for (int i = 0; i < getChildCount(); i++) {
            final View child = getChildAt(i);
            if (child.getVisibility() != GONE) {
                final int childWidth = child.getMeasuredWidth();
                child.layout(childLeft, verticalGravity, childLeft + childWidth, verticalGravity + child.getMeasuredHeight());
                childLeft += childWidth;
            }
        }
    }
}